import { query, DataSource, ConnectorDataSource } from "@/services";
import { useCallback, useEffect, useRef, useState } from "react";
import styled from 'styled-components';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';
import { Button, Tabs, Empty } from "antd";
import { SplitBox } from '@/components/base/split-box';

import { SimpleVTable } from '@/components/table';
// import { appendSql, removeSql } from '@/store/viewer/sqllist';
import { HistorySqlList } from './history-sqlist';

export const SqlQuery = (props: { dataSource: ConnectorDataSource }) => {
    // const dispatch = useDispatch();

    const [activeKey, setActiveKey] = useState<'结果' | '历史'>('结果');

    const [columns, setColumns] = useState<Array<any>>([]);

    const [data, setData] = useState<Array<any>>([]);

    const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor | null>(null);

    const monacoEl = useRef(null);

    useEffect(() => {
        if (monacoEl) {
            setEditor((editor) => {
                if (editor) return editor;

                return monaco.editor.create(monacoEl.current!, {
                    automaticLayout: true,
                    value: '',
                    language: 'sql'
                });
            });
        }

        return () => editor?.dispose();
    }, [monacoEl.current]);

    const action = useCallback((sql: string, index: number) => {
        return (
            <>
                <Button type={'link'} size={'small'} onClick={() => {
                    console.log(sql, index);
                    editor && editor?.setValue(sql);
                }}>使用</Button>
                <Button type={'link'} size={'small'} onClick={() => {
                    console.log(sql, index);
                    // dispatch(removeSql(index));
                }}>删除</Button>
            </>
        );
    }, [editor]);

    return (
        <SplitBox split={'horizontal'}
            minSize={180} size={180} >
            <TopContainer>
                <SQLEditorContainer ref={monacoEl}>
                </SQLEditorContainer>
                <ToolsContainer>
                    <Left>
                        <Tabs
                            style={{
                                marginTop: '15px'
                            }}
                            defaultActiveKey={activeKey}
                            activeKey={activeKey}
                            onChange={(key: string) => {
                                setActiveKey(key as any);
                            }}
                            type="card"
                            size={'small'}
                            items={[
                                {
                                    label: `结果`,
                                    key: `结果`,
                                },
                                {
                                    label: `历史`,
                                    key: `历史`,
                                },
                            ]}
                        />
                    </Left>
                    <Right>
                        <RunButton onClick={async () => {
                            let sql = editor?.getValue();
                            if (!sql || sql == '' || sql.trim() === '') {
                                return;
                            }
                            // dispatch(appendSql({ sql: sql, dbType: props.dataSource.database_type, create_at: new Date().getTime() }));
                            console.log(sql);

                            setActiveKey('结果');
                            //获取数据
                            let data = await query(props.dataSource, sql, [], {})
                            console.log(data);
                            setColumns(data.header)
                            setData(data.values);
                        }}>运&nbsp;&nbsp;行</RunButton>
                    </Right>
                </ToolsContainer>
            </TopContainer>
            <ResultContainer>
                {
                    activeKey === '结果' && (
                        !columns || columns.length <= 0 ? (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={'暂无数据'} />
                        ) : (
                            <SimpleVTable columns={columns} data={data}></SimpleVTable>
                        )
                    )
                }
                {
                    activeKey === '历史' && (
                        <HistorySqlList dbType={props.dataSource.database_type} action={(sql: string, index: number) => {
                            return (
                                <>
                                    <Button type={'link'} size={'small'} onClick={() => {
                                        console.log(sql, index);
                                        editor && editor?.setValue(sql);
                                    }}>使用</Button>
                                    <Button type={'link'} size={'small'} onClick={() => {
                                        console.log(sql, index);
                                        // dispatch(removeSql(index));
                                    }}>删除</Button>
                                </>
                            );
                        }}></HistorySqlList>
                    )
                }
            </ResultContainer>
        </SplitBox>
    );
};

export default SqlQuery;

const TopContainer = styled.div`
    width: 100%;
    height:100%;
    display: flex;
    flex-direction: column;
    border-bottom: 1px solid #d9d9d9;
`;

const SQLEditorContainer = styled.div`
    width: 100%;
    flex: 1;
    background-color: #FFFFFF;
`;

const ToolsContainer = styled.div`
    width: 100%;
    height: 40px;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 0 6px;
    border-top: 1px solid #d9d9d9;
    justify-content: space-between;
`;

const Left = styled.div`
    width:160px;
`;

const ResultContainer = styled.div`
    height: 100%;
    width: 100%;
    overflow: auto;
    flex: 1;
`;


const Right = styled.div`
    height: 100%;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    justify-content: flex-end;
`;

const RunButton = styled.div`
    cursor: pointer;
    margin-top: -1px;
    height: 30px;
    line-height: 30px;
    font-size: 14px;
    font-weight: 900;
    color:red;
    width: 80px;
    background-color: #FFFFFF;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom-left-radius: 6px;
    border-bottom-right-radius: 6px;
`;